package com.elong.android.specialhouse.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.adapter.CitySelectAdapter;
import com.elong.android.specialhouse.adapter.common.BaseViewHolder;
import com.elong.android.specialhouse.adapter.common.MultiItemType;
import com.elong.android.specialhouse.adapter.common.PowerAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.ApartmentSearchParam;
import com.elong.android.specialhouse.entity.City;
import com.elong.android.specialhouse.entity.RegionResult;
import com.elong.android.specialhouse.request.DestinationSuggestReq;
import com.elong.android.specialhouse.ui.CustomDialogBuilder;
import com.elong.android.specialhouse.ui.LimitedListView;
import com.elong.android.specialhouse.ui.SideBar;
import com.elong.android.specialhouse.ui.TagCloudView;
import com.elong.android.specialhouse.utils.BDLocationManager;
import com.elong.android.specialhouse.utils.FileUtils;
import com.elong.android.specialhouse.utils.PrefUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kaiqi.li
 * @ClassName: ApartmentCitySelectActivity
 * @Description: (公寓城市选择)
 * @date 2015-7-30 下午6:29:37
 */
public class ApartmentCitySelectActivity extends BaseVolleyActivity<IResponse<?>> implements OnItemClickListener, TextWatcher, TagCloudView.OnTagClickListener ,TextView.OnEditorActionListener {


    private static final String TAG = ApartmentCitySelectActivity.class.getSimpleName();
    private static final int GET_CITIES_DATA_START = 100;
    private static final int GET_CITIES_DATA_FINISH = 200;


    /**
     * Activity入口标识
     * 1 ： 从发布房源位置信息界面跳转过来
     * 2 ： 点击城市搜索框跳转过来
     */
    private static final int FROM_PUBLISH_HOUSE_LOCATION = 1;
    private static final int FROM_SEARCH_CITY = 2;
    private int fromWhere ;
    private boolean isSearching = false ;
    /**
     * 等待框对象
     */
    private CustomDialogBuilder _loadingDialog;
    /**
     * popupwindow
     */
    private final static int DROPDOWN_OFFX = 0;
    private final static int DROPDOWN_OFFY = 0;

    /**
     * 城市列表显示不同的item
     */
    private final static int CITY_LIST_NAME = 1;
    private final static int CITY_LIST_SEPARATOR_LETTER = 2;

    /***************** View *****************/

    /**
     * 历史搜索记录界面 上次搜索和当前位置（作为城市列表ListView的header）
     */
    private View mCityHistoryView;

    /**
     * 城市列表
     */
    private ListView mCityListView;
    private CitySelectAdapter<City> mCityListAdapter;

    /**
     * 右侧字母索引栏
     */
    private SideBar mRightSideBar;

    /**
     * 点击字母栏后的提示
     */
    private TextView mOverlayTip;

    /**
     * 搜索输入框
     */
    private EditText mSearchInputEt;

    /**
     * 搜索框右侧删除按钮
     */
    private ImageView mClearSearchInputIv;

    /**
     * 搜索Suggest弹出框
     */
    private PopupWindow mSearchSuggestWindow;

    /**
     * 搜索Suggest列表
     */
    private ListView mSuggestListView;

    /***************** DATA *****************/

    /**
     * 搜索历史数据
     */
    private LimitedListView mSearchHistorysView;
    private PowerAdapter<RegionResult> mSearchHistorysAdapter;
    private List<RegionResult> mSearchHistorys;

    /**
     * suggest 数据
     */
    private List<RegionResult> mSuggestDatas;

    /**
     * 城市列表信息数据
     */
    private List<City> mAllCities;

    /**
     * 热门城市信息数据
     */
    private List<City> mHotCities;


    private HandlerThread handlerThread;
    private Handler htHandler;
    private Handler uiHandler;
    private String addressCityId;
    private String addressCityName ;

    @Override
    protected void initContentView() {

        setContentView(R.layout.act_city_select);
        handlerThread = new HandlerThread("getCitiesData");
        handlerThread.start();
        htHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int what = msg.what;
                if (what == GET_CITIES_DATA_START) {
                    showWaittingDialog();
                    mAllCities = initLocalCitiesData();
                    uiHandler.sendEmptyMessage(GET_CITIES_DATA_FINISH);
                }
            }
        };
        uiHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == GET_CITIES_DATA_FINISH) {
                    dismissWaittingDialog();
                    setupHeaderView(fromWhere);
                    setupCitySelectListView();
                }
            }
        };
        getCitiesData();

        fromWhere = getIntent().getIntExtra(AppConstants.ACTIVITY_KEY_FROM_WHERE,FROM_SEARCH_CITY) ;

        this.mCityListView = (ListView) findViewById(R.id.city_select_list);
        this.mRightSideBar = (SideBar) findViewById(R.id.sidebar_city_select);
        this.mOverlayTip = (TextView) findViewById(R.id.city_select_key);

        setupTitlebar();

    }

    private void getCitiesData() {
        if (htHandler != null) {
            htHandler.sendEmptyMessageAtTime(GET_CITIES_DATA_START, 0);
        }
    }

    /**
     * 设置标题栏
     */
    private void setupTitlebar() {
        if (fromWhere == FROM_SEARCH_CITY) {
            this.mSearchInputEt = (EditText) findViewById(R.id.apartment_search_input_keyword);
            this.mSearchInputEt.addTextChangedListener(this);
            this.mClearSearchInputIv = (ImageView) findViewById(R.id.apartment_search_input_keyword_clear_iv);
            this.mClearSearchInputIv.setOnClickListener(this);
        }else if (fromWhere == FROM_PUBLISH_HOUSE_LOCATION) {
            findViewById(R.id.ll_city_select_input).setVisibility(View.GONE);
            TextView titleView = (TextView) findViewById(R.id.title);
            titleView.setVisibility(View.VISIBLE);
            titleView.setText(R.string.choose_cities);
        }
    }

    /**
     * 设置城市列表的显示以及右侧SideBar的绑定
     */
    private void setupCitySelectListView() {

        MultiItemType<City> multiItemType = new MultiItemType<City>() {
            @Override
            public int getItemViewType(int position, City t) {
                if (!t.isSeparator()) {
                    return CITY_LIST_NAME;
                }
                return CITY_LIST_SEPARATOR_LETTER;
            }

            @Override
            public int getLayoutId(int position, City t) {
                if (!t.isSeparator()) {
                    return R.layout.item_select_city_name;
                }
                return R.layout.item_city_select_seciton_letter;
            }

            @Override
            public int getViewTypeCount() {
                return 2;
            }
        };

        mCityListAdapter = new CitySelectAdapter<City>(ApartmentCitySelectActivity.this, mAllCities, multiItemType) {
            @Override
            protected void convert(BaseViewHolder holder, City item) {
                switch (holder.mItemLayoutId) {
                    case R.layout.item_select_city_name:
                        holder.setText(R.id.item_city_name, item.getCityName());
                        break;
                    case R.layout.item_city_select_seciton_letter:
                        holder.setText(R.id.item_city_select_separator, item.getCityName());
                        break;
                    default:
                        break;
                }
            }

            /**
             * SideBar的回调
             */
            @Override
            public int getPositionForSection(String section) {
                if ("历史搜索".equals(section) || "热门城市".equals(section)) {
                    return 0;
                }
                for (int i = 0; i < mAllCities.size(); i++) {
                    if (mAllCities.get(i).isSeparator() && section.equals(mAllCities.get(i).getCityName())) {
                        return i + 1;
                    }
                }
                return -1;
            }
        };
        mCityListView.addHeaderView(mCityHistoryView);
        mCityListView.setAdapter(mCityListAdapter);
        mCityListView.setOnItemClickListener(this);
        mRightSideBar.setListView(mCityListView, mCityListAdapter);
        mRightSideBar.setTextView(mOverlayTip);
        mCityListAdapter.notifyDataSetChanged();

    }

    /**
     * 设置cityListView的header （上次搜索、当前位置和热门城市的显示）
     */
    private void setupHeaderView(int fromWhere) {

        if (fromWhere == FROM_SEARCH_CITY) { //从公寓列表页跳转过来的城市搜索
            mSearchHistorys = getSearchHistorisFromSP() == null ? new ArrayList<RegionResult>() : new ArrayList<RegionResult>(getSearchHistorisFromSP());
            mCityHistoryView = LayoutInflater.from(this).inflate(R.layout.header_city_select_activity_layout, null, false);

            TextView currentAddress = (TextView) mCityHistoryView.findViewById(R.id.tv_cityselect_address);
            if (!TextUtils.isEmpty(BDLocationManager.getInstance().getAddressName())) {
                currentAddress.setText(BDLocationManager.getInstance().getAddressName());
                addressCityName = BDLocationManager.getInstance().mCityName;
                addressCityId = Utils.retriveCityIdByCityName(this, addressCityName);
                currentAddress.setOnClickListener(this);
            } else {
                currentAddress.setText("获取当前位置信息失败");
            }
            TagCloudView tcvHotCities = (TagCloudView) mCityHistoryView.findViewById(R.id.cityselect_hot_cities);
            mSearchHistorysView = (LimitedListView) mCityHistoryView.findViewById(R.id.ll_search_history_container);
            if (null != mSearchHistorys) {
                mSearchHistorysView.setVisibility(View.VISIBLE);
            } else {
                mSearchHistorysView.setVisibility(View.GONE);
            }
            mSearchHistorysAdapter = new PowerAdapter<RegionResult>(ApartmentCitySelectActivity.this, R.layout.item_select_city_name, mSearchHistorys) {
                @Override
                protected void convert(BaseViewHolder holder, RegionResult item) {
                    holder.setText(R.id.item_city_name, item.composedName);
                }
            };
            mSearchHistorysView.setAdapter(mSearchHistorysAdapter);
            mSearchHistorysView.setOnItemClickListener(this);
            tcvHotCities.setTags(mHotCities);
            tcvHotCities.setOnTagClickListener(this);
        }else if(fromWhere == FROM_PUBLISH_HOUSE_LOCATION) { //从发布房源的发布房源地址跳转过来的城市选择
            mCityHistoryView = LayoutInflater.from(this).inflate(R.layout.header_city_select_activity_from_pushlish, null, false);
            TagCloudView tcvHotCities = (TagCloudView) mCityHistoryView.findViewById(R.id.cityselect_hot_cities);
            tcvHotCities.setTags(mHotCities);
            tcvHotCities.setOnTagClickListener(this);
        }
    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);

        JSONObject result = (JSONObject) JSONObject.parse(((StringResponse) t).getContent());
        boolean isHandlerError = handleIsError(request, result);
        if (isHandlerError) {
            return;
        }
        switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
            case destinationSuggest:
                isSearching = false ;
                if (null == result) {
                    return ;
                }
                onSearchFinish(result);
                break ;
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_head_back:
                if (mSearchSuggestWindow != null && mSearchSuggestWindow.isShowing()) {
                    mSearchSuggestWindow.dismiss();
                }
                back();
                break ;
            case R.id.apartment_search_input_keyword_clear_iv:
                mSearchInputEt.setText("");
                if (mSearchSuggestWindow != null && mSearchSuggestWindow.isShowing()) {
                    mSearchSuggestWindow.dismiss();
                }
                break;
            case R.id.tv_cityselect_address :
                if (TextUtils.isEmpty(addressCityName) || TextUtils.isEmpty(addressCityId)) {
                    return ;
                }
                if (fromWhere == FROM_SEARCH_CITY) {
                    RegionResult region = new RegionResult() ;
                    region.parentId = addressCityId ;
                    region.parentNameCn = addressCityName;
                    region.composedName = addressCityName;
                    goApartmentListActivity(region);
                }else if (fromWhere == FROM_PUBLISH_HOUSE_LOCATION) {
                    City city = new City() ;
                    city.setCityId(addressCityId);
                    city.setCityName(addressCityName);
                    back2PublishLocation(city);
                }
                break ;
            default:
                break;
        }
        super.onClick(v);
    }

    /**
     * 获取Suggest数据后的处理与展示
     */
    @SuppressLint("InflateParams")
    private void onSearchFinish(JSONObject jo) {
        View view = LayoutInflater.from(this).inflate(R.layout.city_select_dropdown_list, null);
        if (this.mSuggestListView == null) {
            mSuggestListView = (ListView) view.findViewById(R.id.search_dropdown_list);
        }
        mSuggestDatas = initSuggestDatas(jo);
//        if (mSuggestDatas == null || mSuggestDatas.size() < 1) {
//            return;
//        }
        PowerAdapter<RegionResult> adapter = new PowerAdapter<RegionResult>(ApartmentCitySelectActivity.this, R.layout.item_city_select, mSuggestDatas) {
            @Override
            protected void convert(BaseViewHolder holder,
                                   final RegionResult item) {
                // TODO Auto-generated method stub
                holder.setText(R.id.cityselect_item_name, item.composedName);
                holder.setOnClickListener(R.id.cityselect_item_name, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //保存到本地历史搜索中
                        PrefUtils.saveSearchHistories(ApartmentCitySelectActivity.this, item);
                        if (mSearchSuggestWindow.isShowing()) {
                            mSearchSuggestWindow.dismiss();
                        }
                        mSearchInputEt.setText(item.composedName);
                        //更新页面上的历史记录显示
                        mSearchHistorysAdapter.replaceAll(getSearchHistorisFromSP());
                        goApartmentListActivity(item);
                    }
                }) ;
            }
        };
        mSuggestListView.setAdapter(adapter);
//        mSuggestListView.setOnItemClickListener(this);

        if (mSearchSuggestWindow == null) {
            mSearchSuggestWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            // mSearchSuggestWindow.setBackgroundDrawable(new ColorDrawable(android.R.color.darker_gray));
            mSearchSuggestWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.white)));

            mSearchSuggestWindow.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        mSuggestListView.onTouchEvent(event);
                        mSearchSuggestWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                        mSearchSuggestWindow.update();
                    }
                    return false;
                }
            });
//            mSearchSuggestWindow
            mSearchSuggestWindow.setOutsideTouchable(true);
            mSearchSuggestWindow.setWindowLayoutMode(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            mSearchSuggestWindow
                    .setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            mSearchSuggestWindow.showAsDropDown(mSearchInputEt, DROPDOWN_OFFX,
                    DROPDOWN_OFFY);

        }
        if (mSearchSuggestWindow.isShowing()) {
            mSearchSuggestWindow.update();
        } else {
            mSearchSuggestWindow
                    .setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            mSearchSuggestWindow.showAsDropDown(mSearchInputEt, DROPDOWN_OFFX,
                    DROPDOWN_OFFY);
        }

    }

    /**
     * 解析Suggest数据
     *
     * @return
     */
    private List<RegionResult> initSuggestDatas(JSONObject jo) {
        List<RegionResult> datas = new ArrayList<RegionResult>();
        if (jo.containsKey(JSONConstants.ATTR_REGION_RESPONSE_DATA)) {
            datas = JSONArray.parseArray(jo.getString(JSONConstants.ATTR_REGION_RESPONSE_DATA), RegionResult.class);
        }
        return datas;

    }

    /**
     * 读取本地cities数据
     */
    private List<City> initLocalCitiesData() {
        List<City> cities = null;
        String data = FileUtils.getCitiesData(ApartmentCitySelectActivity.this);
        if (data != null && !TextUtils.isEmpty(data)) {
            JSONObject jo = JSONObject.parseObject(data);
            boolean isError = jo.getBooleanValue(JSONConstants.ATTR_ISERROR);
            if (!isError) {
                cities = JSONArray.parseArray(jo.getString(JSONConstants.ATTR_ALL_CITY_LIST), City.class);
                mHotCities = JSONArray.parseArray(jo.getString(JSONConstants.ATTR_HOT_CITY_LIST), City.class);
            }
        }
        //设置ABC分隔符后返回
        return FileUtils.addCityListSeparator(cities);
    }

    /**
     *
     * @Title: showWaittingDialog
     * @Description: TODO(显示等待框)
     * @param
     * @return void
     * @throws
     */
    private void showWaittingDialog() {
        if (_loadingDialog == null) {
            _loadingDialog = new CustomDialogBuilder(
                    ApartmentCitySelectActivity.this,
                    CustomDialogBuilder.LOADING_DIALOG_IDS, 0);
            _loadingDialog.setCancelable(false);
            _loadingDialog.setMessage(R.string.loadingDynamicTips10);
        }
        try {
            _loadingDialog.show();
        } catch (Exception e) {
        }
    }

    /**
     *
     * @Title: dismissWaittingDialog
     * @Description: TODO(隐藏等待框)
     * @param
     * @return void
     * @throws
     */
    private void dismissWaittingDialog() {
        if (_loadingDialog != null && _loadingDialog.isShowing()) {
            _loadingDialog.dismiss();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (parent == null) {               //点击历史搜索
            goApartmentListActivity(mSearchHistorys.get(position));
        } else if (parent == mCityListView) {     //点击城市列表

            if (position > 0) {   //屏蔽Header和ABC分隔线的点击事件
                position = position - 1;       //与数据集下标对应起来
                if (!mAllCities.get(position).isSeparator()) {
                    switch (fromWhere) {
                        case FROM_PUBLISH_HOUSE_LOCATION :
                            back2PublishLocation(mAllCities.get(position));
                            break ;
                        case FROM_SEARCH_CITY :
                            City city = mAllCities.get(position);
                            RegionResult region = new RegionResult() ;
                            region.parentId = city.getCityId();
                            region.parentNameCn = city.getCityName() ;
                            region.composedName = city.getCityName() ;
                            PrefUtils.saveSearchHistories(this, region);
                            mSearchHistorysAdapter.replaceAll(getSearchHistorisFromSP());
                            goApartmentListActivity(region);
                            break;
                        default:
                            break;
                    }

                }
            }
        } else {

        }
    }

    /**
     * 热门城市点击事件监听
     *
     * @param position
     */
    @Override
    public void onTagClick(int position) {
        if (fromWhere == FROM_SEARCH_CITY) {
            City city = mHotCities.get(position);
            RegionResult region = new RegionResult();
            region.parentId = city.getCityId();
            region.parentNameCn = city.getCityName();
            region.composedName = city.getCityName();
            PrefUtils.saveSearchHistories(this, region);
            mSearchHistorysAdapter.replaceAll(getSearchHistorisFromSP());
            goApartmentListActivity(region);
        }else if (fromWhere == FROM_PUBLISH_HOUSE_LOCATION) {
            back2PublishLocation(mHotCities.get(position));
        }

    }

    /**
     * 跳转到公寓列表页
     */
    private void goApartmentListActivity(RegionResult item) {
        //todo
        ApartmentSearchParam param = new ApartmentSearchParam() ;
        param.CityID = item.parentId ;
        param.CityName = item.parentNameCn ;
        param.AreaType = item.regionType ;
        param.AreaId = item.regjionId ;
        param.AreaName = item.regionNameCn ;
        Intent intent = new Intent(ApartmentCitySelectActivity.this, ApartmentListActivity.class);
        intent.putExtra("ApartmentSearchParam",param);
        startActivity(intent);
        back();
    }

    /**
     * 返回到房源位置信息发布界面
     */
    private void back2PublishLocation(City city){
        Intent intent = new Intent();
        intent.putExtra(AppConstants.KEY_CITY_NAME,city.getCityName());
        intent.putExtra(AppConstants.KEY_CITY_ID,city.getCityId());
        setResult(RESULT_OK, intent);
        back();
    }

    /**
     * 从sharepreference中读取历史搜索信息
     */
    private List<RegionResult> getSearchHistorisFromSP() {
        List<RegionResult> results = null ;
        String histories = PrefUtils.getSearchHistories(this);
        if (!TextUtils.isEmpty(histories)) {
            results = JSONArray.parseArray(histories, RegionResult.class);
        }
        return results ;
    }

    /**
     * TextWatcher
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        String keyword = s.toString();
        keyword = keyword.trim();
        if (s == null || s.length() == 0 || "".equals(s.toString().trim())) {
            mClearSearchInputIv.setVisibility(View.GONE);
        } else {
            if (mSearchInputEt.hasFocus()) {
                mClearSearchInputIv
                        .setVisibility(View.VISIBLE);
            }
        }
        if (TextUtils.isEmpty(keyword)) {
            if (mSearchSuggestWindow !=null && mSearchSuggestWindow.isShowing()) {
                mSearchSuggestWindow.dismiss();
            }
            return;
        }
        DestinationSuggestReq req = new DestinationSuggestReq();
        req.Search = keyword;
        if (!isSearching) {
            requestHttp(req, ApartmentAPI.destinationSuggest, StringResponse.class);
            isSearching = true ;
        }

    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH
                || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            // TODO
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerThread.quit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mSearchSuggestWindow != null && mSearchSuggestWindow.isShowing()) {
                mSearchSuggestWindow.dismiss();
            }
            back();
        }
        return super.onKeyDown(keyCode, event);
    }
}
